<template>
  <el-row type="flex" class="setting-flow-container">
    <div id="task-flow-guide"></div>
    <!--S 工单流程轴 -->
    <div class="setting-flow-axis" id="setting-flow-axis-guide"  v-loading="loading && isHaveNodeFlowAuth">
      <template v-if="!isHaveNodeFlowAuth">
      <el-row
        class="flow-axis-step-box"
        type="flex"
        justify="space-between"
        v-for="key in Object.keys(flowMap)"
        :key="key"
        @click.native="clickFlow(key)">
        <el-row
          class="flow-axis-step"
          :class="[currFlow === key && 'active', (!taskFlowData.taskTypeConfig.flowSetting[key].state && !flowMap[key].isSystem) && 'disabled']"
          type="flex" justify="space-between">
          <div>
            <i :class="['iconfont', flowMap[key].icon]" :style="{color: key === 'close' && '#F56C6C'}"></i>
            {{flowMap[key].name}}
          </div>
          <div v-if="taskFlowData.taskTypeConfig.flowSetting[key].state || flowMap[key].isSystem" class="open-tag">{{$t('common.base.alreadyOpen')}}</div>
        </el-row>
        <div class="open-btn" @click.stop>
          <el-switch v-model="taskFlowData.taskTypeConfig.flowSetting[key].state" v-if="!flowMap[key].isSystem"/>
        </div>
      </el-row>
    </template>
      <template v-else>
        <biz-flow-process-chart
          vertical 
          :showScaleBar="false" 
          :data="flowProcessList" 
          :nodeTypeList="nodeTypeList" 
          :currentNode="currentNode"
          :customCreateNode="handleCustomCreateNode" 
          :beforeDeleteNode="beforeDeleteNode"
          :beforeAddNode="beforeAddNode"
          @node-content-click="handleNodeContentClick"
          @handleNodePopoverTypeClick="handleNodePopoverTypeClick"
        />
      </template>
    </div>
    <!--E 工单流程轴 -->
    <!--S 流程设置 -->
    <div class="setting-flow-main" :class="settingFlowMainClassNames">
      <div class="setting-flow-main-title">
        {{flowDesc}}
        <div class="common-set" v-if="currFlow == 'normal'"> 
          <div class="common-setting-btn" v-if="isAlreadySavedCommon">
            <template v-if="!isEditState">
              <span  @click="editCommonNodes">{{ $t('common.form.setting.flowNodeSetting.des2') }}</span>
              <!-- <span @click="cancelNodeCommonSetting">{{ $t('common.form.setting.flowNodeSetting.des3') }}</span> -->
            </template>
            <div class="common-setting-edit" v-else>
              <el-button  size="mini" @click="onCancelEdit" >{{$t('common.base.cancel')}}</el-button>
              <el-button size="mini" type="primary" @click="onSubmitCommon">{{$t('common.base.makeSure')}}</el-button>
            </div>
          </div>
          <template v-else>
            <el-checkbox :true-label="1" :false-label="0" v-model="currentNode.isCommon" >{{ $t('common.form.setting.flowNodeSetting.des1') }} </el-checkbox>
            <el-tooltip class="item" effect="dark" :content="$t('common.form.setting.flowNodeSetting.msg')" placement="top">
              <i class="iconfont icon-jieshishuoming"></i>
            </el-tooltip>
          </template>
        </div>
      </div>
      <div class="setting-flow-main-content" id="setting-flow-main-content-guide">
        <flow-setting
          ref="flowSettingRef"
          :isUpdate="isUpdate"
          :task-type-id="taskTypeId"
          :type="currFlow"
          :flow-setting="isEditState ? commonData.flowSetting : flowSetting"
          :task-type-config="taskFlowData.taskTypeConfig"
          :flow-card-list="flowCardList"
          :flowProcessList="flowProcessList"
          :currentNode="isEditState ? commonData.currentNode : currentNode"
          :isEditState="isEditState"
          :isNewNormalNode="isNewNormalNode"
          @flowCardChange="flowCardChange"
          @saveSubmit="saveSubmit"
          style="height: 100%"/>
      </div>
    </div>
    <!--E 流程设置 -->
  </el-row>
</template>

<script>
import _ from 'lodash';
/** api */
import * as SettingApi from '@src/api/SettingApi.ts';
import * as TaskApi from '@src/api/TaskApi.ts';
import * as SettingTaskApi from '@src/api/SettingTaskApi';
/** components */
import FlowSetting from '../components/FlowSetting.vue';

import { convertDataToParams, logDataToParams } from '../util';
// 新存储工具方法
import { storageGet, storageSet } from '@src/util/storage.ts';
/* enum */
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
import { isBasicEditionHidePay } from '@shb-lib/version'

import { TASK_FLOW_SETTING_GUIDE } from '@src/component/guide/taskSettingStore';
/** mixin */
import FlowNewNodeMixin from '@src/modules/setting/task/taskTypeSetting/flow/util/FlowNewNodeMixin.js'

import flowMap from '../flowMap';
import { getRootWindowInitData } from '@src/util/window'
const rootWindowInitData = getRootWindowInitData()
// utils
import { isConnectorCard } from '@service/CardService.ts';

export default {
  name: 'flow-setting-panel',
  inject: ['taskFlowData'],
  mixins: [FlowNewNodeMixin],
  props: {
    taskTypeId: {
      type: String,
      default: ''
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    customerSatisfaction() {
      // 展示回访问卷方案设置
      return rootWindowInitData?.customerSatisfaction
    },
    settingFlowMainClassNames() {
      return [
        'setting-flow-main-' + this.currFlow
      ]
    },
    /**节点描述信息 */
    flowDesc() {
      return this.flowMap?.[this.currFlow]?.desc ?? '';
    },
    /**节点设置数据 */
    flowSetting() {
      return this.isHaveNodeFlowAuth ? this.currentNode?.data : this.taskFlowData.taskTypeConfig.flowSetting[this.currFlow];
    },
  },
  watch: {
    isBasicEditionHidePay: {
      immediate: true,
      handler(newValue, _) {
        if (!newValue) {
          this.flowMap = flowMap
        } else {
          // 基础版是否隐藏结算工单流程
          let baseFlowMap = flowMap;
          delete(baseFlowMap['cost']);
          this.flowMap = baseFlowMap;
        }
      }
    }
  },
  data() {
    return {
      currFlow: 'create', // 当前设置的流程
      open: false,

      flowMap,
      flowCardList: [], // 所有节点添加的附加组件列表
      oldFlowCardList: [], // 旧的附加组件+连接器数据
    }
  },
  methods: {
    clickFlow(type) {
      this.currFlow = type;
    },
    saveSubmit(){
      this.submit({});
    },
    /** 保存流程设置 (暴露的方法) */
    async submit(otherParams) {
      try {
        // 处理系统节点数据
        if(this.isHaveNodeFlowAuth) {
          // 校验必填项
          if(this.checkProcessingRequired()) return true

          this.handleSaveSystemProcessing()
        }
        let params = convertDataToParams(this.taskFlowData.taskTypeConfig);
        if (params.flowSetting.review.state && this.customerSatisfaction && !params.flowSetting.review.questionId && params.flowSetting.review.questionId !== 0) {
          this.$platform.notification({
            title: this.$t('task.setting.taskTypeSetting.flow.tabs.tip2'),
            type: 'error'
          });
          return true
        }

        let levelSetting = params.flowSetting?.[this.currFlow] || {}
  
        //   // 无需审批
        if (levelSetting?.level === 0) {
          levelSetting.leader = ''
          levelSetting.conditions = []
          levelSetting.approvers = []
        }


        if (this.currFlow ==='allot') {
          // 指派内的转派特殊处理
          // 无需审批的话，所有的人员和条件都清除
          if (levelSetting.transferApprove.level === 0) {
            levelSetting.transferApprove.leader = ''
            levelSetting.transferApprove.conditions= []
            levelSetting.transferApprove.approvers = []
          } 
          // 如果转派是选中的无需审批或者一级审批，那二级multiApproverSetting的值也要清除

          if (levelSetting.transferApprove.level === 0 || levelSetting.transferApprove.level === 1) {
            levelSetting.transferApprove.multiApproverSetting = [
              {
                leader: '',
                approvers: [],
                conditions: []
              }
            ]
          }
          // 如果设置转派和指派一致的话，需要重新设值
          if (levelSetting.transferApprove.level === 3) {
            // 如果转派设置保持和指派一致的话，高级审批处理
              levelSetting.transferApprove.conditions = levelSetting.conditions
          }
        }

        if (levelSetting?.conditions && levelSetting?.conditions.length) {
          levelSetting?.conditions.forEach((item) => {
            if (item && item.length) {
              item.forEach((ele) => {
                if (ele.module === 'task_receipt_amount') {
                  ele.conditionItem.fieldName = ele.conditionItem.field.id
                  ele.conditionItem.ruleName = ele.conditionItem.field.ruleName
                }
              })
            }
          })
        }

        if (levelSetting?.multiApproverSetting && levelSetting?.multiApproverSetting.length >0) {
          if (levelSetting.multiApproverSetting[0]?.conditions && levelSetting.multiApproverSetting[0].conditions.length > 0) {
            levelSetting.multiApproverSetting[0].conditions.forEach((item) => {
              if (item && item.length) {
                item.forEach((ele) => {
                  if (ele.module === 'task_receipt_amount') {
                    ele.conditionItem.fieldName = ele.conditionItem.field.id
                    // 最后重新赋值
                    ele.conditionItem.ruleName = ele.conditionItem.field.ruleName
                  }
                })
              }
            })
          }
       }

      //  高级审批处理
       if (levelSetting?.level === 4) {
        levelSetting.leader = ''
        levelSetting.conditions = []
        // level恢复为0
        levelSetting.level = 0
       } else {
        levelSetting.vipApprove = 0
       // levelSetting.vipApproveSetting = {}
       }

      // 保存自定义节点
      if(this.isHaveNodeFlowAuth) {
        const createTaskRes = await this.createTaskFlowNode()
        if(createTaskRes === true) return true
      }

        params = {
          ...params,
          ...otherParams,
          satisfactionGray: this.customerSatisfaction
        };
                
        let res = await SettingApi.saveProcess(params);
        if(res.status == 1) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }


        // 保存节点添加的附加组件
        this.submitCard(otherParams);

        this.$platform.notification({
          title: this.$t('common.base.saveSuccess'),
          type: 'success'
        });
        this.$customerOperateLog(logDataToParams('flow', this.taskFlowData));//记录用户操作日志
      } catch (error) {
        console.error('error', error);
      }
    },
    /* 保存附加组件数据 */
     async submitCard(otherParams) {
      try {
        const flowCardList = _.cloneDeep(this.flowCardList);
        // 附加组件权限设置 更改设置权限的方式 authInfo需传空或不传 
        const objectIds = [];
        flowCardList.forEach(x => {
          x.authInfo = [];
          if(x.isSetObject === 'add') { // add添加 set设置过使用权限的
            objectIds.push(x.id);
            delete x.isSetObject;
          }
        });

        const params = {
          taskTypeId: this.taskTypeId,
          cardInfo: this.flowCardList,
          ...otherParams
        }
        let res = await SettingTaskApi.batchSaveTaskCard(params); 
        if(res.status === 0) {
          SettingTaskApi.initDefaultTaskRange({
            taskTypeId: this.taskTypeId,
            objectIds
          })
          .then(() => {})
          .catch(e => console.log('SettingTaskApi.initDefaultTaskRange: ', e))
        }else {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
      } catch (error) {
        console.error(error);
      }
    },
    /** 检查内容是否有修改 (暴露的方法) */
    checkModified() {
      let {taskTypeConfig, initTaskTypeConfig} = this.taskFlowData;
      const formCheck = JSON.stringify(taskTypeConfig) != JSON.stringify(initTaskTypeConfig);
      const cardCheck = JSON.stringify(this.flowCardList) != JSON.stringify(this.oldFlowCardList);
      // 校验新流程节点
      const flowProcessListCheck = JSON.stringify(this.flowProcessList) != JSON.stringify(this.oldFlowProcessList);

      return formCheck || cardCheck || flowProcessListCheck;
    },
    /** 同步初始数据 (暴露的方法) */
    resetInit() {
      this.taskFlowData.taskTypeConfig = _.cloneDeep(this.taskFlowData.initTaskTypeConfig);
    },
    // 附加组件信息变更
    flowCardChange(e) {
      if(e) {
        this.flowCardList = e;
      }else {
        this.fetchTaskType();
      }
    },
    async fetchTaskType(emptySet) {
      try {
        if(!this.taskTypeId) return;
          const { status, message, data } = await TaskApi.getTaskType({ id: this.taskTypeId});
          if( status == 0 ){
              if(JSON.stringify(data.cardSetting) !== '{}' && data.cardSetting.cardInfo){
                  const cardInfo = data?.cardSetting?.cardInfo || [];

                  this.flowCardList = emptySet ? cardInfo : _.unionBy(cardInfo, this.flowCardList, 'id');

                  const newConnectorList = cardInfo.filter(item => isConnectorCard(item));
                  // 筛序出最新添加的连接器
                  if(this.oldFlowCardList.length) {
                    const item = newConnectorList.find((x)=> !(this.oldFlowCardList.some((v)=>v.id === x.id)));
                    // 设置add 供后续保存时初始化使用权限
                    if(item) {
                      this.flowCardList.forEach(x => {
                        if(x.id === item.id) {
                          x.isSetObject = 'add';
                        }
                      })
                    }
                  }

                  this.oldFlowCardList = _.cloneDeep(this.flowCardList);
              }
          }     
      } catch (err) {
          console.error('fetch Tasktype => err', err);
      }
    },
  },
  activated() {
    this.fetchTaskType(true);
  },
  mounted() {
    console.log('开始更新！1')
    this.$nextTick(async() => {
      this.fetchTaskType();
    })
    // this.$nextTick(async() => {
    //   const guideStore = await storageGet(TASK_FLOW_SETTING_GUIDE, 0, StorageModuleEnum.Task);
    //   if (guideStore > 0) return this.$Guide().destroy('task-flow-guide');

    //   this.$Guide([{
    //     id: 'task-flow-guide',
    //     content: '流程节点可被选中，选中后可设置每个节点的业务规则',
    //     haveStep: true,
    //     needCover: true,
    //     direction: 'row',
    //     outsideParent: true,
    //     inside: true,
    //     nowStep: 1,
    //     domObj: () => {
    //       return document.getElementById('setting-flow-axis-guide')
    //     },
    //     insideDom: () => {
    //       return document.getElementById('setting-flow-axis-guide').getElementsByClassName('flow-axis-step')[0]
    //     },
    //     lastFinish: true
    //   }, {
    //     id: 'task-flow-guide',
    //     content: '可在新建工单节点设置工单表单，本次更新提升了表单控件的能力',
    //     haveStep: true,
    //     needCover: true,
    //     direction: 'row',
    //     outsideParent: true,
    //     inside: true,
    //     nowStep: 2,
    //     domObj: () => {
    //       return document.getElementById('setting-flow-main-content-guide').getElementsByClassName('form-design-center')[0]
    //     },
    //     lastFinish: true
    //   },
    //   //  {
    //   //   id: 'task-flow-guide',
    //   //   content: '流程中「通用规则」部分的设置，在所有节点均生效',
    //   //   haveStep: true,
    //   //   needCover: true,
    //   //   direction: 'row',
    //   //   outsideParent: true,
    //   //   inside: true,
    //   //   nowStep: 3,
    //   //   domObj: () => {
    //   //     return document.getElementById('setting-flow-main-content-guide').getElementsByClassName('setting-common')[0]
    //   //   },
    //   //   insideDom: () => {
    //   //     return document.getElementById('setting-flow-main-content-guide').getElementsByClassName('setting-common')[0].getElementsByClassName('setting-specific-form')[1]
    //   //   },
    //   //   lastFinish: true
    //   // }, 
    //   {
    //     id: 'task-flow-guide',
    //     content: '在「完成工单」节点设置回执表单',
    //     haveStep: true,
    //     needCover: true,
    //     direction: 'row',
    //     outsideParent: true,
    //     inside: true,
    //     nowStep: 3,
    //     domObj: () => {
    //       return document.getElementById('setting-flow-axis-guide')
    //     },
    //     insideDom: () => {
    //       return document.getElementById('setting-flow-axis-guide').getElementsByClassName('flow-axis-step')[4]
    //     },
    //     lastFinish: true
    //   }], 0, '', (e) => {
    //     return new Promise((resolve, reject) => {
    //       resolve()
    //     })
    //   }).create()
    //     .then(res_ => { 
    //       if(res_) storageSet(TASK_FLOW_SETTING_GUIDE, '4', StorageModuleEnum.Task);
    //     })
    // })
  },
  components: {
    [FlowSetting.name]: FlowSetting
  }
}
</script>

<style lang="scss" scoped>
.setting-flow-container{
    width: 100%;
    min-height: calc(100vh - 55px);
    padding: 12px;
    .setting-flow-axis{
        width: 298px;
        min-height: 100%;
        padding: 20px;
        background: #FFFFFF;
        border-radius: 4px;
        .flow-axis-step-box{
          width: 100%;
          .open-btn{
            position: absolute;
            top: 40px;
            right: 0;
          }
          &:not(:last-child){
              .flow-axis-step::after{
                  content: "";
                  position: absolute;
                  left: 50%;
                  bottom: -31px;
                  display: block;
                  transform: translateX(-50%);
                  width: 1px;
                  height: 30px;
                  background: #E6E6E6;
              }
          }
        }
        .flow-axis-step{
            cursor: pointer;
            position: relative;
            width: 188px;
            height: 44px;
            margin-top: 30px;
            padding: 10px;
            line-height: 22px;
            font-size: 14px;
            background: #FFFFFF;
            border-radius: 4px;
            border: 1px solid #D9D9D9;
            div:nth-child(1){
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            }
            i{
                margin-right: 3px;
                color: $color-primary;
            }
            .open-tag{
                width: 52px;
                height: 22px;
                text-align: center;
                color: #67C23A;
                background: #E1F3D8;
                border-radius: 11px;
                border: 1px solid #CFEDC0;
            }
            &.disabled{
                color: #999999;
                background: #F2F2F2;
                border: 1px solid #E6E6E6;
                i{
                    color: #999999;
                }
            }
            &.active{
               background: $color-primary-light-1;
                border: 1px solid $color-primary;
            }
        }
    }
    
    .setting-flow-main{
        flex: 1;
        width: 100%;
        min-height: 100%;
        padding-left: 12px;
        &-title{
          width: 100%;
          height: 40px;
          line-height: 40px;
          text-align: center;
          font-style: 14px;
           background: $color-primary-light-1;
          .common-set {
            text-align: right;
            margin-right:17px;
            color: #595959;
            .iconfont {
              margin-left: 4px;
            }
            .common-setting-btn {
              span {
                color: $color-primary;
                cursor: pointer;
                &:first-child {
                  // margin-right: 12px;
                }
              }
              .common-setting-edit {
                button {
                  border-radius: 4px;
                }
              }

            }
          }
        }
        &-content{
            height: calc(100% - 40px);
        }
    }
}
</style>
<style lang="scss">
.setting-flow-main-content {
  & > .flow-setting {
    & > .flow-setting-left {
      & > .flow-setting-form-preview.form-design-main {
        & > .form-design-center {
          & > .form-design-phone {
            height: calc(100% - 130px);
          }
        }
      }
    }
  }
}
</style>